package com.iamk.util;

import java.io.File;
import java.io.FileFilter;

public class ExtensionsFilter implements FileFilter 
{
	public static final ExtensionsFilter IMAGE_FILTER = new ExtensionsFilter(new String[] {".png", ".jpg", ".bmp"});
	public static final ExtensionsFilter DATA_FILTER = new ExtensionsFilter(new String[]{".arff" , ".csv","txt"});
    private char[][] extensions;

    private ExtensionsFilter(String[] extensions)
    {
        int length = extensions.length;
        this.extensions = new char[length][];
        for (String s : extensions)
        {
            this.extensions[--length] = s.toCharArray();
        }
    }

    @Override
    public boolean accept(File file)
    {
    	if(file.isDirectory())
    		return true;
        char[] path = file.getPath().toCharArray();
        for (char[] extension : extensions)
        {
            if (extension.length > path.length)
            {
                continue;
            }
            int pStart = path.length - 1;
            int eStart = extension.length - 1;
            boolean success = true;
            for (int i = 0; i <= eStart; i++)
            {
                if ((path[pStart - i] | 0x20) != (extension[eStart - i] | 0x20))
                {
                    success = false;
                    break;
                }
            }
            if (success)
                return true;
        }
        return false;
    }
}
